<template>
  <RouterView />
</template>
<script setup>
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import WebSocketService from '@/services/WebSocketService.js';
import { unreadCount } from "@/router/index.js";
let webSocketService;
const initWebSocket = () => {
  const user = JSON.parse(localStorage.getItem("user") || '{}');
  const token = user.token;
  const userId = user.id;
  if (!token) {
    console.error('Token 不存在，无法建立 WebSocket 连接');
    return;
  }
  const wsUrl = `ws://localhost:8080/plant/socket?userId=${userId}`;
  webSocketService = new WebSocketService(wsUrl);
  webSocketService.on('open', () => {
    console.log('WebSocket 连接已打开');
  });
  webSocketService.on('message', (data) => {
    if (data.msgType && data.msg) {
      unreadCount.value++;
      console.log('新的总未读消息数:', unreadCount.value);
    }
  });
  webSocketService.on('error', (error) => {
    console.error('WebSocket 错误:', error);
  });
  webSocketService.on('close', (event) => {
    console.log('WebSocket 连接已关闭', event);
  });
};

// 页面加载时检查登录状态并初始化 WebSocket
onMounted(() => {
  const user = JSON.parse(localStorage.getItem("user") || '{}');
  if (user.token) {
    initWebSocket();
  }
});
</script>


